package com.gxa.utils;


import com.gxa.exception.NotAllowExtException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件上传工具类
 */
public class UploadFileUtil {

    public static Map<String,Object> formData = new HashMap();

    public static boolean upload(HttpServletRequest request){
        //1.创建文件上传工厂对象
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        //2.创建文件上传的组件
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        //3.设置文件上传的编码集
        servletFileUpload.setHeaderEncoding("UTF-8");
        try {
            //整体文件最大不能超过多少 B KB 100MB
            servletFileUpload.setSizeMax(100*1024*1024);
            //单个文件最大不能超过多少
            servletFileUpload.setFileSizeMax(5*1024*1024);
            //4.获取请求对象塞入到上传组件中
            List<FileItem> fileItems = servletFileUpload.parseRequest(request);
            for (FileItem fileItem : fileItems){
                 if(fileItem.isFormField()){
                     //普通表单元素key value塞入到formData对象
                     formData.put(fileItem.getFieldName(),fileItem.getString());
                 }else{
                     InputStream is = fileItem.getInputStream();//获取文件的输入流
                     //源文件名称
                     String sourceFileName = fileItem.getName();//图片源文件名称

                     //目标文件名称：202110291431020001.jpg
                     String tarGetFileName = tarGetFileName(sourceFileName);
                     //D:/2021-bjWorkSpace/upload_dowload_project/upload
//                     String uploadDiskPath = request.getRealPath("/");//获取当前项目的绝对路径E:/upload  E:\
                     String uploadDiskPath = "D:\\";
                     String relativePath = createUploadFilePath(uploadDiskPath);//  /upload/
                     //创建一个输出流实现文件的上传功能
                     OutputStream os = new FileOutputStream(uploadDiskPath+relativePath+File.separator+tarGetFileName);
                     byte[] by = new byte[1024];
                     int len;
                     while((len = is.read(by)) != -1){
                         os.write(by,0,len);
                     }
                     os.flush();
                     os.close();
                     is.close();
                     //把相对路径的图片地址塞给formData
                     formData.put(fileItem.getFieldName(),relativePath+tarGetFileName);
                 }

            }
            //文件上传成功
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 创建文件，将相对路径返回。
     */
    public static String createUploadFilePath(String uploadDiskPath){
        String filePath = File.separator+"upload"+File.separator;
        File file = new File(uploadDiskPath+filePath);
        if(!file.exists()){//如果E没有upload目录就创建一个，有就算了
            file.mkdirs();
        }
        return filePath;
    }

    /**
     * 传入源文件名称 zxy.jpg 生成 202110291431020001.jpg
     * @param sourceFileName
     * @return
     */
    public static String tarGetFileName(String sourceFileName){
        String fileName = GenerateSequenceUtil.generateSequenceNo();
        String ext = sourceFileName.substring(sourceFileName.lastIndexOf(".")); //.jpg
        //上传.jpg .png .gif
        String allowExt = ".jpg|.png|.gif";
        if(allowExt.lastIndexOf(ext) == -1){//未找到了
              throw new NotAllowExtException("不允许上传此类型文件");
        }
        //目标文件名称
        String tarGetFileName = fileName+ext;
        return tarGetFileName;
    }


}
